package com.sprucetec.live.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Sets;
import com.sprucetec.live.common.util.*;
import com.sprucetec.live.entity.LiveAttachment;
import com.sprucetec.live.entity.LiveOperateLog;
import com.sprucetec.live.enums.LoadOSSFileType;
import com.sprucetec.live.service.LiveOperateLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.apache.tomcat.util.http.fileupload.util.Streams.checkFileName;

/**
 * @author chenkai
 * @date 2020/3/30 6:08 下午
 * @description:
 */
@Slf4j
@RestController
@RequestMapping(value = "/common")
public class CommonController {


    @Value("${OSS.tag}")
    private String tag;

    @Value("${OSS.key}")
    private String key;

    @Value("${OSS.upload.url}")
    private String attachmentUploadUrl;

    @Value("${OSS.download.url}")
    private String attachmentDownloadUrl;

    private static Set<String> fileTypeSet = Sets.newHashSet("doc", "docx", "xls", "xlsx", "jpg", "png", "pdf", "rar", "zip", "eml");

    @Autowired
    private LiveOperateLogService liveOperateLogService;
    /**
     * 上传附件
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadAttachment", method = {RequestMethod.GET, RequestMethod.POST})
    public ServiceResult<LiveAttachment> uploadAttachment(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ServiceResultUtil.fail(RespCode.ERROR, "附件为空，请重新上传");
        }
        int pointIndex = file.getOriginalFilename().lastIndexOf(".");
        String fileType = org.apache.commons.lang.StringUtils.substring(file.getOriginalFilename(), pointIndex+1);
        if (!fileTypeSet.contains(fileType.toLowerCase())) {
            return ServiceResultUtil.fail(RespCode.ERROR, "只能上传 doc, docx, xls, xlsx, jpg, png, pdf, rar, zip, eml 格式的文件");
        }
        String fileName = checkFileName(file.getOriginalFilename());
        if (StringUtils.isBlank(fileName)) {
            return ServiceResultUtil.fail(RespCode.ERROR, "请上传文件名有效的文件");
        }
        InputStream in = null;
        try {
            in = file.getInputStream();
            String fileCode = FileEncryptUtil.encrypt(in, null);
            Map extraHeader = OssUtil.createOssHeader(tag, key, System.currentTimeMillis(), "admin", "mams", fileCode, null);
            String result = OssUtil.uploadFile(attachmentUploadUrl, file, extraHeader);
            JSONObject uploadResult = JSONObject.parseObject(result);
            if (uploadResult.getIntValue("ret") != 0) {
                return ServiceResultUtil.fail(RespCode.ERROR, "上传文件失败");
            }
            JSONObject dataJson = uploadResult.getJSONObject("data");
            LiveAttachment liveAttachment = new LiveAttachment();
            liveAttachment.setFileId(dataJson.getString("fid"));
            liveAttachment.setFileFurl(dataJson.getString("furl"));
            liveAttachment.setFileName(fileName);
            liveAttachment.setFileType(fileType);
            liveAttachment.setFileSize(file.getSize());
            return ServiceResultUtil.success(liveAttachment);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("附件上传发生错误", e);
        }finally {
            try {
                if(in != null){
                    in.close();
                }
            } catch (IOException e) {
                log.error("附件上传发生错误", e);
            }
        }
        return ServiceResultUtil.fail(RespCode.ERROR, "上传文件失败");
    }

    /**
     * 下载附件
     * @param fid fileId 首位不带 /
     * @param fileName
     */
    @RequestMapping(value = "/downloadAttchment", method = {RequestMethod.GET, RequestMethod.POST})
    public void downloadAttchment(@RequestParam(required = true, value = "fid") String fid,
                                  @RequestParam(required = false, value = "fileName") String fileName,
                                  HttpServletResponse response) {
        try {
            OssUtil.downloadAttachment(fileName, attachmentDownloadUrl + "/" + fid, LoadOSSFileType.DOWNLOAD, response);
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }

    /**
     * 预览附件
     * @param fid
     * @param fileName
     * @param response
     */
    @RequestMapping(value = "/previewAttachment", method = {RequestMethod.GET, RequestMethod.POST})
    public void previewAttachment(@RequestParam(required = true, value = "fid") String fid,
                                  @RequestParam(required = false, value = "fileName") String fileName,
                                  HttpServletResponse response) {
        try {
            OssUtil.downloadAttachment(fileName, attachmentDownloadUrl + "/" + fid, LoadOSSFileType.PREVIEW, response);
        } catch (Exception e) {
            log.error("文件下载失败", e);
        }
    }

    /**
     * 获取操作日志
     * @return
     */
    @PostMapping("getOperateLogList")
    public ServiceResult<List<LiveOperateLog>> getLiveOperateLogList(@RequestBody LiveOperateLog liveOperateLog) {
        return ServiceResultUtil.success(liveOperateLogService.getOperateLogList(liveOperateLog));
    }
}
